<!--
 * @Descripttion:
 * @version:
 * @Author: ybac
 * @Date: 2022-11-04 10:37:34
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-06-09 14:23:39
-->
<template>
  <j-modal
    :visible.sync='modal.visible'
    :width='800'
    :title='modal.title'
    :fullscreen.sync='modal.fullscreen'
    :switchFullscreen='modal.switchFullscreen'
    @cancelVisible='cancel'
  >
    <template>
      <div class='form-wrap'>
        <a-form :form='form' @submit='submit' class='form'>
          <a-row class='form-row' :gutter='[48, 16]'>
            <a-col :span='22'>
              <a-form-item label='账号' prop='username' :wrapper-col='{ span: 20 }' :label-col='{ span: 4 }'>
                <a-input
                  v-decorator="[
                    'username',
                    {
                      rules: [
                        { required: true, message: '请输入账号' },
                        {
                          message: '该值不可用，系统中已存在！',
                          validator: (rule, value, callback) => validateCheckUserNameRule(value, queryId, callback),
                        },
                      ],
                    },
                  ]"
                  placeholder='请输入'
                  :maxLength='30'
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row class='form-row' :gutter='[48, 16]'>
            <a-col :span='22'>
              <a-form-item label='姓名' prop='realname' :wrapper-col='{ span: 20 }' :label-col='{ span: 4 }'>
                <a-input
                  v-decorator="[
                    'realname',
                    {
                      rules: [{ required: true, message: '请输入姓名' }],
                    },
                  ]"
                  placeholder='请输入'
                  :maxLength='15'
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row class='form-row' :gutter='[48, 16]'>
            <a-col :span='22'>
              <a-form-item label='手机号' prop='phone' :wrapper-col='{ span: 20 }' :label-col='{ span: 4 }'>

                <a-input
                  v-decorator="[
                    'phone',
                    {
                      rules: [
                        { required: true, message: '请输入手机号' },
                        {
                          pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
                          message: '请输入正确的手机号',
                        },
                        {
                          message: '该值不可用，系统中已存在！',
                          validator: (rule, value, callback) =>
                            validateCheckUserPhoneRule(value, queryId, callback),
                        },
                      ],
                    },
                  ]"
                  placeholder='请输入'
                  :maxLength='11'
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter='[48, 16]'>
            <a-col :span='22'>
              <a-form-model-item
                label='部门'
                prop='selecteddeparts'
                :wrapper-col='{ span: 20 }'
                :label-col='{ span: 4 }'
              >
                <j-select-depart-f
                  v-decorator="['selecteddeparts', { rules: [{ required: true, message: '请选择部门' }] }]"
                  @change='changeParent'
                  :multi='true'
                ></j-select-depart-f>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter='[48, 16]'>
            <a-col :span='22'>
              <a-form-model-item
                label='角色'
                prop='selectedroles'
                :wrapper-col='{ span: 20 }'
                :label-col='{ span: 4 }'
              >
                <a-select v-decorator="['selectedroles']" allowClear mode='multiple' placeholder='请选择'>
                  <a-select-option v-for='item in roleList' :key='item.id' :value='item.id'>
                    {{ item.roleName }}
                  </a-select-option>
                </a-select>
                <!-- <j-select-multiple
                  placeholder="请选择"
                  v-decorator="['selectedroles']"
                  :options="roleList"
                  optionLabel="roleName"
                  optionValue="id"
                /> -->
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </template>
    <template slot='footer'>
      <a-button key='back' @click='cancel'> 取消</a-button>
      <a-button key='submit' type='primary' @click='submit' :loading='loadingForm'> 提交</a-button>
    </template>
  </j-modal>
</template>

<script>
import { validateCheckUserNameRule, validateCheckUserPhoneRule } from '@/utils/util'
import JAreaLinkage from '@comp/jeecg/JAreaLinkage'
import { postAction } from '@/api/manage'
import { getAction } from '../../../api/manage'

export default {
  name: 'formPage',
  props: ['tenantId'],
  components: {
    JAreaLinkage
  },
  data() {
    return {
      validateCheckUserNameRule,
      validateCheckUserPhoneRule,
      form: this.$form.createForm(this, { name: 'coordinated' }),
      modal: {
        title: '新建用户',
        visible: false,
        fullscreen: false,
        switchFullscreen: false
      },
      submitApi: '',
      loadingForm: false,
      queryId: '',
      roleList: [],
      itemInfo: {}
    }
  },
  watch: {
    'modal.visible'(val) {
      if (val) {
        getAction('/sys/role/queryByTenantId', { tenantId: this.$store.getters.tenantid }).then((res) => {
          if (res.code == 200) {
            this.roleList = res.result || []
          }
        })
      }
    }
  },
  methods: {
    changeParent(v) {
      this.$nextTick(() => {
        this.form.validateFields(['selecteddeparts'])
      })
    },
    // 新增表单
    open(pid) {
      console.log(pid, 'pid')
      this.modal.title = '新建用户'
      this.submitApi = ''
      this.queryId = ''
      this.modal.visible = true
    },
    // 编辑表单
    editor(v) {
      this.modal.title = '编辑用户'
      this.modal.visible = true
      this.submitApi = ''
      getAction('/sys/user/queryById', { id: v.id }).then((res) => {
        if (res.code == 200) {
          let resForm = res.result
          this.itemInfo = resForm
          this.$nextTick(() => {
            this.form.setFieldsValue({
              username: resForm.username,
              realname: resForm.realname,
              phone: resForm.phone,
              selecteddeparts: resForm.departIds,
              selectedroles: resForm.roleIds ? resForm.roleIds.split(',') : undefined
            })
            this.queryId = resForm.id
          })
        }
      })
    },
    // 提交表单
    submit() {
      this.loadingForm = true
      let submitApi = '/sys/user/add'
      this.form.validateFields((err, formValues) => {
        if (!err) {
          let params = {}
          // 过滤空值、undefined、null
          for (let key in formValues) {
            if (!!formValues[key] || formValues[key] == 0) {
              params[key] = formValues[key]
            }
          }
          if (this.modal.title == '编辑用户') {
            params.id = this.queryId
            submitApi = '/sys/user/edit'
            params.tenantIds = this.$store.getters.tenantid
            let that = this
            if (params.username != that.itemInfo.username) {
              that.$antdConfirm({
                title: '该账号已修改，密码将被初始化，初始化密码为手机号后六位',
                onOk() {
                  that.itemInfo.username = params.username
                  that.submit()
                },
                onCancel() {
                  that.loadingForm = false
                }
              })
              return
            }
          }
          params.isTenant = '1'
          if (params.selectedroles) {
            params.selectedroles = params.selectedroles.join(',')
          }
          postAction(submitApi, params, 180000)
            .then((res) => {
              if (res.success) {
                this.$antdMessage.success(res.message)
                this.$emit('success')
                this.cancel()
              } else {
                this.$antdMessage.error(res.message)
              }
              this.loadingForm = false
            })
            .catch((err) => {
              this.loadingForm = false
            })
        } else {
          this.loadingForm = false
        }
      })
    },
    // 关闭表单
    cancel() {
      this.form.resetFields()
      this.loadingForm = false
      this.modal.visible = false
    }
  }
}
</script>

<style lang='less' scoped>
/deep/ .ant-modal-body {
  padding: 12px !important;

  .ant-form-item {
    margin-bottom: 0;
  }
}

/deep/ .ant-modal-mask {
  z-index: 1 !important;
}

/deep/ .ant-modal-wrap {
  z-index: 1 !important;
}

.form-wrap {
  background: #fff;
  height: 100%;
  padding: 24px;
  overflow-y: scroll;

  .code-btn {
    position: absolute;
    right: 0;
    top: -50.5px;
  }
}
</style>
